/*
 * @Date: 2023-03-23 11:16:22
 * @LastEditors: Chuying
 * @LastEditTime: 2023-03-24 11:28:14
 * @Description: 异常过滤
 */
import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
} from '@nestjs/common';

import { Request, Response } from 'express';

@Catch(HttpException)
export class HttpFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp(); // 获取请求上下文
    const request: Request = ctx.getRequest(); // 获取请求上下文中的request对象
    const response: Response = ctx.getResponse(); // 获取请求上下文中的response对象
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR; // 获取异常状态码

    // 设置错误信息
    const message = exception.message
      ? exception.message
      : `${
          status >= 500
            ? '服务器错误（Service Error）'
            : '客户端错误（Client Error）'
        }`;

    console.log('exception=========>', exception);
    const errRes = exception.getResponse();
    response.status(status).json({
      result: errRes,
      status,
      success: false,
      message,
      time: new Date().getTime(),
      path: request.url,
    });
  }
}
